package db

import (
	"encoding/json"
	"ulcdkey/tool"
)

// 获取所有渠道列表
func (this *Channel) GetChannelList() (as []*Channel, err error) {
	rows, err := db.Query("select id,copChannelId,channelName,platform from `channel`")
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		a := new(Channel)
		err = rows.Scan(&a.Id, &a.CopChannelId, &a.ChannelName, &a.Platform)
		if err != nil {
			return
		}
		as = append(as, a)
	}

	return
}

// 获取对应平台的渠道列表
func (this *Channel) GetChannelListByPlatform() (as []*Channel, err error) {
	rows, err := db.Query("select id,copChannelId,channelName,platform from `channel` where platform = ?", this.Platform)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		a := new(Channel)
		err = rows.Scan(&a.Id, &a.CopChannelId, &a.ChannelName, &a.Platform)
		if err != nil {
			return
		}
		as = append(as, a)
	}

	return
}

// 新增渠道
func (this *Channel) AddChannel(info *tool.VisitUserInfo) (err error) {

	row, err := db.Exec("insert into `channel` (copChannelId,channelName,platform) values (?,?,?)", this.CopChannelId, this.ChannelName, this.Platform)
	if err != nil {
		return
	}

	// 记录日志
	int64s, err := row.LastInsertId()
	if err != nil {
		return
	}
	this.Id = int(int64s)

	b, _ := json.Marshal(this)
	serverLog := &ServerLog{UserId: info.Uid, UserName: info.UserName, Platform: info.Platform, ActionType: LogActionType.Add, Module: "渠道管理", OldContent: "", NewContent: string(b)}
	serverLog.RecordLog()
	return
}

// 修改渠道
func (this *Channel) UpdateChannel(info *tool.VisitUserInfo) (err error) {
	old, err := this.GetChannelById(this.Id)
	if err != nil {
		return
	}

	_, err = db.Exec("update `channel` set copChannelId = ?,channelName = ?,platform = ? where id = ?", this.CopChannelId, this.ChannelName, this.Platform, this.Id)
	if err != nil {
		return
	}

	// 记录日志
	nb, _ := json.Marshal(this)
	ob, _ := json.Marshal(old)
	serverLog := &ServerLog{UserId: info.Uid, UserName: info.UserName, Platform: info.Platform, ActionType: LogActionType.Update, Module: "游戏管理", OldContent: string(ob), NewContent: string(nb)}
	serverLog.RecordLog()
	return
}

// 删除渠道
func (this *Channel) DelChannel(info *tool.VisitUserInfo) (err error) {

	old, err := this.GetChannelById(this.Id)
	if err != nil {
		return
	}

	_, err = db.Exec("delete from `channel` where id = ?", this.Id)
	if err != nil {
		return
	}

	// 记录日志
	ob, _ := json.Marshal(old)
	serverLog := &ServerLog{UserId: info.Uid, UserName: info.UserName, Platform: info.Platform, ActionType: LogActionType.Delete, Module: "游戏管理", OldContent: string(ob), NewContent: ""}
	serverLog.RecordLog()

	return
}

// 根据id获取渠道
func (this *Channel) GetChannelById(id int) (res *Channel, err error) {
	res = new(Channel)
	err = db.QueryRow("select id,copChannelId,channelName,platform from `channel` where id = ?", id).Scan(&res.Id, &res.CopChannelId, &res.ChannelName, &res.Platform)
	if err != nil {
		return
	}
	return
}
